package com.daxia.bumall.web.controller.admin;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daxia.bumall.common.Logs;
import com.daxia.bumall.common.ProfitType;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.OrderStatisticsDTO;
import com.daxia.bumall.dto.UserStatisticsDTO;
import com.daxia.bumall.model.User;
import com.daxia.bumall.service.OrderStatisticsService;
import com.daxia.bumall.service.UserStatisticsService;
import com.daxia.bumall.support.OrderQueue;
import com.daxia.bumall.util.DateUtils;
import com.daxia.bumall.util.SpringSecurityUtils;
import com.daxia.bumall.web.controller.BaseController;

@Controller
@RequestMapping(value = "/admin/index", produces = "text/html;charset=UTF-8")
public class AdminIndexController extends BaseController {
	@Autowired
	private OrderQueue orderQueue;
	@Autowired
	private OrderStatisticsService orderStatisticsService;
	@Autowired
	private UserStatisticsService userStatisticsService;
	

    @RequestMapping("index_v3")
    public String index_v3(Map<String, Object> map) throws Exception {
        User user = (User) SpringSecurityUtils.getCurrentUser();
        OrderStatisticsDTO dto = new OrderStatisticsDTO();
        Logs.COMMON.debug("user.getType(): " + user.getType());
        if (user.getType() == UserType.City.getValue()) {
        	return setCityOperatorInfo(map, user, dto);
        } else if (user.getType() == UserType.DecorateCompany.getValue() || user.getType() == UserType.Designer.getValue()) {
        	dto.setUserId(user.getId());
        	dto.setStart(0);
            dto.setEnd(3);
            //三个月的
            List<OrderStatisticsDTO> threeMonth = orderStatisticsService.findForMonth(dto);
            map.put("threeMonth", threeMonth);
            if (threeMonth != null && threeMonth.size() > 0) {
            	//当月的
            	OrderStatisticsDTO currentMonth = threeMonth.get(0);
            	map.put("currentMonth", currentMonth);
            }
            //三年的
            List<OrderStatisticsDTO> threeYear = orderStatisticsService.findForYear(dto);
            if (threeYear != null && threeYear.size() > 0) {
            	//当年
            	OrderStatisticsDTO currentYear = threeYear.get(0);
            	map.put("currentYear", currentYear);
            }
            //三季度的
            List<OrderStatisticsDTO> threeQuarter = orderStatisticsService.findForQuarter(dto);
            if (threeQuarter != null && threeQuarter.size() > 0) {
            	//当年
            	OrderStatisticsDTO currentQuarter = threeQuarter.get(0);
            	map.put("currentQuarter", currentQuarter);
            }
            return "admin/index_v3_sub";
        } else {
        	dto.setStart(0);
            dto.setEnd(3);
            //三个月的
            List<OrderStatisticsDTO> threeMonth = orderStatisticsService.findForMonth(dto);
            map.put("threeMonth", threeMonth);
            if (threeMonth != null && threeMonth.size() > 0) {
            	//当月的
            	OrderStatisticsDTO currentMonth = threeMonth.get(0);
            	map.put("currentMonth", currentMonth);
            	 if (threeMonth.size() > 1) {
                 	//上月的
                 	OrderStatisticsDTO lastMonth = threeMonth.get(1);
                 	//统计金额
                 	if(lastMonth.getAmount().doubleValue()>0){
                 		BigDecimal increase=currentMonth.getAmount().subtract(lastMonth.getAmount());
                     	Double increaseAmountPercentMonth=increase.divide(lastMonth.getAmount(),4,BigDecimal.ROUND_HALF_UP).doubleValue()*100;
                     	map.put("increaseAmountPercentMonth", Double.parseDouble(new DecimalFormat("0.00").format(increaseAmountPercentMonth)));
                 	}else{
                 		map.put("increaseAmountPercentMonth", Double.parseDouble(new DecimalFormat("0.00").format(currentMonth.getAmount().doubleValue()*100)));
                 	}
                 	//统计订单数量
                 	if(lastMonth.getQuantity().doubleValue()>0){
                 		Integer increase=currentMonth.getQuantity()-lastMonth.getQuantity();
            			String increaseQuantityPercentMonth=new DecimalFormat("0.00").format(increase.doubleValue()/lastMonth.getQuantity()*100);
                     	map.put("increaseQuantityPercentMonth", Double.parseDouble(increaseQuantityPercentMonth));
                 	}else{
                 		map.put("increaseQuantityPercentMonth", currentMonth.getQuantity()*100);
                 	}
                 	//统计总订单数量
                 	if(null!=lastMonth.getAllQuantity()&&lastMonth.getAllQuantity().doubleValue()>0){
                 		Integer increase=currentMonth.getAllQuantity()-lastMonth.getAllQuantity();
            			String increaseQuantityPercentMonth=new DecimalFormat("0.00").format(increase.doubleValue()/lastMonth.getAllQuantity()*100);
                     	map.put("increaseAllQuantityPercentMonth", Double.parseDouble(increaseQuantityPercentMonth));
                 	}else{
                 		map.put("increaseAllQuantityPercentMonth", currentMonth.getAllQuantity()*100);
                 	}
                 }
            }
           
            //三年的
            List<OrderStatisticsDTO> threeYear = orderStatisticsService.findForYear(dto);
            if (threeYear != null && threeYear.size() > 0) {
            	//当年
            	OrderStatisticsDTO currentYear = threeYear.get(0);
            	map.put("currentYear", currentYear);
            	if(threeYear.size()>1){
            		//上一年的
            		OrderStatisticsDTO lastYear=threeYear.get(1);
            		if(lastYear.getQuantity()>0){
            			Integer increase=currentYear.getQuantity()-lastYear.getQuantity();
            			String increaseQuantityPercentYear=new DecimalFormat("0.00").format(increase.doubleValue()/lastYear.getQuantity()*100);
                     	map.put("increaseQuantityPercentYear", Double.parseDouble(increaseQuantityPercentYear));
            		}else{
            			map.put("increaseQuantityPercentYear", currentYear.getQuantity()*100);
            		}
            	}
            }
            
            dto.setStart(0);
            dto.setEnd(30);
            List<OrderStatisticsDTO> thirtyDay=orderStatisticsService.findForDay(dto);
            if(thirtyDay!=null && thirtyDay.size()>0){
            	StringBuffer allOrder=new StringBuffer();
            	StringBuffer payOrder=new StringBuffer();
            	allOrder.append("[");
            	payOrder.append("[");
            	for(int i=thirtyDay.size()-1;i>-1;i--){
            		if(i==0){
            			allOrder.append(toOrderJson(thirtyDay.get(i).getMonth(),thirtyDay.get(i).getAllQuantity()));
            			payOrder.append(toOrderJson(thirtyDay.get(i).getMonth(),thirtyDay.get(i).getQuantity()));
            		}else{
            			allOrder.append(toOrderJson(thirtyDay.get(i).getMonth(),thirtyDay.get(i).getAllQuantity())+",");
            			payOrder.append(toOrderJson(thirtyDay.get(i).getMonth(),thirtyDay.get(i).getQuantity())+",");
            		}
            	}
            	allOrder.append("]");
            	payOrder.append("]");
            	
            	map.put("allOrder", allOrder.toString());
            	map.put("payOrder", payOrder.toString());
            	
            }
            UserStatisticsDTO todayUser=userStatisticsService.statisticsUserToday();
            UserStatisticsDTO monthUser=userStatisticsService.statisticsUserMoth();
            UserStatisticsDTO yesterdayUser=userStatisticsService.statisticsUserYesterday();
            UserStatisticsDTO lastMonthUser=userStatisticsService.statisticsUserLastMonth();
            map.put("todayUser", todayUser);
            map.put("monthUser", monthUser);
            if(null!=yesterdayUser){
            	if(yesterdayUser.getLoginAmount()>0){
            		int increase=todayUser.getLoginAmount()-yesterdayUser.getLoginAmount();
                	double increasePercentDay=(double)increase/yesterdayUser.getLoginAmount()*100;
                	map.put("increasePercentDay", Double.parseDouble(new DecimalFormat("0.00").format(increasePercentDay)));
            	}else{
            		map.put("increasePercentDay", todayUser.getLoginAmount()*100);
            	}
            }
            if(null!=lastMonthUser){
            	if(lastMonthUser.getLoginAmount()>0){
            		int increase=monthUser.getLoginAmount()-lastMonthUser.getLoginAmount();
                	double increasePercentMonth=(double)increase/lastMonthUser.getLoginAmount()*100;
                	map.put("increasePercentMonth", Double.parseDouble(new DecimalFormat("0.00").format(increasePercentMonth)))	;
            	}else{
            		map.put("increasePercentMonth", monthUser.getLoginAmount()*100);
            	}
            }
		}
        return "admin/index_v3_admin";
    }

    private String toOrderJson(String moth,Integer quantity){
    	StringBuffer order=new StringBuffer();
    	order.append("[gd(");
    	order.append(moth.replace("-", ","));
    	order.append("),");
    	order.append(quantity+"]");
    	return order.toString();
    }
	private String setCityOperatorInfo(Map<String, Object> map, User user, OrderStatisticsDTO dto) {
		//运营商
        	dto.setUserId(user.getId());
        	dto.setStart(0);
            dto.setEnd(3);
            dto.setCity(user.getCity());
            //三个月的
            List<OrderStatisticsDTO> threeMonth = orderStatisticsService.findForMonth(dto);
            map.put("threeMonth", threeMonth);
            if (threeMonth != null && threeMonth.size() > 0) {
            	//当月的
            	OrderStatisticsDTO currentMonth = threeMonth.get(0);
            	map.put("currentMonth", currentMonth);
            }
            //三年的
            List<OrderStatisticsDTO> threeYear = orderStatisticsService.findForYear(dto);
            if (threeYear != null && threeYear.size() > 0) {
            	//当年
            	OrderStatisticsDTO currentYear = threeYear.get(0);
            	map.put("currentYear", currentYear);
            }
            //三季度的
            List<OrderStatisticsDTO> threeQuarter = orderStatisticsService.findForQuarter(dto);
            if (threeQuarter != null && threeQuarter.size() > 0) {
            	//当年
            	OrderStatisticsDTO currentQuarter = threeQuarter.get(0);
            	map.put("currentQuarter", currentQuarter);
            }
            
            
            {
	            // 总的子帐号和总的收益
	            int subAccountCount = userService.countSubAccounts(getCurrentUserDTO().getId(), null, null);
	            double subAccountProfit = profitService.totalProfitByTypeAndUser(ProfitType.AddCompany, getCurrentUserDTO().getId(), null, null);
	            map.put("subAccountCount", subAccountCount);
	            map.put("subAccountProfit", subAccountProfit);
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            {
            	// 这个月的
            	Date start = DateUtils.getBeginingOfAMonth(new Date());
            	Date end = new Date();
            	int subAccountCount = userService.countSubAccounts(getCurrentUserDTO().getId(), start, end);
	            double subAccountProfit = profitService.totalProfitByTypeAndUser(ProfitType.AddCompany, getCurrentUserDTO().getId(), start, end);
	            map.put("month1", dateFormat.format(start));
	            map.put("subAccountCount_month1", subAccountCount);
	            map.put("subAccountProfit_month1", subAccountProfit);
            }
            {
            	// 上个月的
            	Date date = DateUtils.getBeginingOfAMonth(new Date());
            	date = org.apache.commons.lang3.time.DateUtils.addDays(date, -1);
            	Date start = DateUtils.getBeginingOfAMonth(date);
            	Date end = DateUtils.getEndOfAMonth(date);
            	
            	int subAccountCount = userService.countSubAccounts(getCurrentUserDTO().getId(), start, end);
	            double subAccountProfit = profitService.totalProfitByTypeAndUser(ProfitType.AddCompany, getCurrentUserDTO().getId(), start, end);
	            map.put("month2", dateFormat.format(start));
	            map.put("subAccountCount_month2", subAccountCount);
	            map.put("subAccountProfit_month2", subAccountProfit);
            }
            {
            	// 上上个月的
            	Date date = DateUtils.getBeginingOfAMonth(new Date());
            	date = org.apache.commons.lang3.time.DateUtils.addDays(date, -1); // 上个月
            	date = DateUtils.getBeginingOfAMonth(date);
            	date = org.apache.commons.lang3.time.DateUtils.addDays(date, -1); // 上上个月
            	Date start = DateUtils.getBeginingOfAMonth(date);
            	Date end = DateUtils.getEndOfAMonth(date);
            	
            	int subAccountCount = userService.countSubAccounts(getCurrentUserDTO().getId(), start, end);
	            double subAccountProfit = profitService.totalProfitByTypeAndUser(ProfitType.AddCompany, getCurrentUserDTO().getId(), start, end);
	            map.put("month3", dateFormat.format(start));
	            map.put("subAccountCount_month3", subAccountCount);
	            map.put("subAccountProfit_month3", subAccountProfit);
            }
            
            // 近三个月的子帐号数及收益数
            List<OrderStatisticsDTO> subAccountThreeMonth = orderStatisticsService.findSubAccountForMonth(dto);
            map.put("subAccountThreeMonth", subAccountThreeMonth);
            
            dto.setCity(user.getCity());
            //三个月的
            List<OrderStatisticsDTO> threeMonthSub = orderStatisticsService.findForMonth(dto);
            map.put("threeMonthSub", threeMonthSub);
            if (threeMonthSub != null && threeMonthSub.size() > 0) {
            	//当月的
            	OrderStatisticsDTO currentMonthSub = threeMonthSub.get(0);
            	map.put("currentMonthSub", currentMonthSub);
            }
            //三年的
            List<OrderStatisticsDTO> threeYearSub = orderStatisticsService.findForYear(dto);
            if (threeYearSub != null && threeYearSub.size() > 0) {
            	//当年
            	OrderStatisticsDTO currentYearSub = threeYearSub.get(0);
            	map.put("currentYearSub", currentYearSub);
            }
            //三季度的
            List<OrderStatisticsDTO> threeQuarterSub = orderStatisticsService.findForQuarter(dto);
            if (threeQuarterSub != null && threeQuarterSub.size() > 0) {
            	//当年
            	OrderStatisticsDTO currentQuarterSub = threeQuarterSub.get(0);
            	map.put("currentQuarterSub", currentQuarterSub);
            }
            return "admin/index_v3";
	}
    
}	
